#!/home/idn-lee/applications/AutoWallPaper/bin/python3
# -*-coding:utf-8-*-
import subprocess
import os

import time
import random

import ImageTools
import Setting
import DownBingWallpaper
import DownUnSplashWallpaper


import importlib,sys
importlib.reload(sys)
#sys.setdefaultencoding('utf8')

if not os.path.isdir(Setting.temppath):
    os.mkdir(Setting.temppath)


def main():

    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + '：开始运行')

    subprocess.run('/usr/bin/rm %s*'% (Setting.wallpath),shell=True)

    # 读取配置文件的信息
    tmp_wall = Setting.temppath+'/wall.jpg'
    watermark = ImageTools.getWatermarkImage()
    source=''
    loop=0

    while loop<10:
        try:
            if random.random() > 0.5:
                  DownUnSplashWallpaper.downNow(tmp_wall)
                  source='bing'
            else:
                 DownUnSplashWallpaper.downNow(tmp_wall)
                 source='unsplash'
            ImageTools.changeSize(tmp_wall)
            new_wallpath = ImageTools.brand(tmp_wall, watermark)
            real_wallpath = Setting.wallpath + 'wallpaper_' + str(int(round(time.time() * 1000))) + '_' + source + '.jpg'
            subprocess.run('/usr/bin/cp %s %s' % (new_wallpath, real_wallpath),shell=True)
            subprocess.run('/usr/bin/dbus-send --dest=com.deepin.daemon.Appearance /com/deepin/daemon/Appearance --print-reply com.deepin.daemon.Appearance.SetCurrentWorkspaceBackground string:"file:///%s"'% (real_wallpath),shell=True)
            print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + "：运行成功")  
             # for monitor in Setting.monitorlist:
             #     subprocess.getstatusoutput('dbus-send --dest=com.deepin.daemon.Appearance /com/deepin/daemon/Appearance --print-reply com.deepin.daemon.Appearance.SetCurrentWorkspaceBackground string:"%s" string:"file:///%s"'% (monitor,real_wallpath))
            break
        except Exception as e:
             print(e)
             print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + "：失败，重试") 
             loop=loop+1
             time.sleep(10)
   
if __name__ == __name__:
    main()
